#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
第1阶段逻辑完整验证脚本
详细验证所有第1阶段步骤，包括Cookie处理、轮播导航、车型发现
"""

import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import TimeoutException, NoSuchElementException

class Stage1Verifier:
    """第1阶段逻辑验证器"""
    
    def __init__(self):
        self.setup_driver()
        self.discovered_cars = set()
        self.pagination_history = []
        self.click_history = []
        
    def setup_driver(self):
        """设置Chrome WebDriver"""
        chrome_options = Options()
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15')
        
        service = Service(ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.wait = WebDriverWait(self.driver, 10)
    
    def verify_stage1_logic(self):
        """验证第1阶段完整逻辑"""
        try:
            print("🔍 开始第1阶段逻辑完整验证")
            print("="*60)
            
            # 步骤1: 访问目标页面
            url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
            print(f"📖 步骤1: 访问目标页面")
            print(f"   URL: {url}")
            self.driver.get(url)
            time.sleep(3)
            
            # 步骤2: 处理Cookie确认
            print(f"\n🍪 步骤2: 处理Cookie确认")
            cookie_success = self.handle_cookie_consent()
            
            # 步骤3: 分析初始页面状态
            print(f"\n📊 步骤3: 分析初始页面状态")
            self.analyze_initial_state()
            
            # 步骤4: 系统性发现所有车型
            print(f"\n🔄 步骤4: 系统性发现所有车型 (目标: 7个)")
            self.systematic_car_discovery()
            
            # 步骤5: 验证特定车型
            print(f"\n🎯 步骤5: 验证特定车型 'ST Edition'")
            self.verify_st_edition()
            
            # 步骤6: 测试轮播恢复功能
            print(f"\n↩️ 步骤6: 测试轮播恢复功能")
            self.test_carousel_reset()
            
            # 步骤7: 最终验证
            print(f"\n✅ 步骤7: 最终验证和总结")
            self.final_verification()
            
            return True
            
        except Exception as e:
            print(f"❌ 验证过程出错: {e}")
            return False
        finally:
            input("按Enter键关闭浏览器...")
            self.driver.quit()
    
    def handle_cookie_consent(self):
        """处理Cookie确认弹窗"""
        try:
            # 方法1: 查找并隐藏cookie元素
            cookie_selectors = [
                '[class*="cookie"]', '[class*="Cookie"]', '[class*="consent"]',
                '[id*="cookie"]', '[id*="Cookie"]', '[id*="consent"]',
                '.cookie-banner', '.consent-banner', '#cookie-notice'
            ]
            
            hidden_count = 0
            for selector in cookie_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed():
                            self.driver.execute_script("arguments[0].style.display = 'none';", element)
                            hidden_count += 1
                except:
                    pass
            
            if hidden_count > 0:
                print(f"   ✓ 隐藏了 {hidden_count} 个Cookie相关元素")
            else:
                print(f"   ✓ 未发现需要处理的Cookie弹窗")
            
            # 方法2: 查找并点击同意按钮
            accept_buttons = [
                'button[class*="accept"]', 'button[id*="accept"]',
                'button:contains("Accept")', 'button:contains("Agree")',
                'button:contains("同意")', 'button:contains("接受")'
            ]
            
            clicked_count = 0
            for selector in accept_buttons:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed():
                            element.click()
                            clicked_count += 1
                            time.sleep(1)
                except:
                    pass
            
            if clicked_count > 0:
                print(f"   ✓ 点击了 {clicked_count} 个同意按钮")
            
            return True
            
        except Exception as e:
            print(f"   ❌ Cookie处理出错: {e}")
            return False
    
    def analyze_initial_state(self):
        """分析初始页面状态"""
        try:
            # 分析分页指示器
            pagination_info = self.get_pagination_info()
            if pagination_info:
                print(f"   📄 分页指示器: {pagination_info}")
                self.pagination_history.append(pagination_info)
            else:
                print(f"   ⚠️  未找到分页指示器")
            
            # 分析当前可见的车型
            current_cars = self.get_current_cars()
            print(f"   🚗 初始可见车型: {len(current_cars)} 个")
            for car in current_cars:
                print(f"      - {car['name']}: {car['visible']}")
                self.discovered_cars.add(car['name'])
            
            # 分析轮播按钮状态
            self.analyze_carousel_buttons()
            
        except Exception as e:
            print(f"   ❌ 初始状态分析出错: {e}")
    
    def get_pagination_info(self):
        """获取分页指示器信息"""
        try:
            # 方法1: 在按钮容器中查找
            next_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="next"]')
            parent = next_button.find_element(By.XPATH, '..')
            text = parent.text.strip()
            
            if 'of' in text.lower():
                return text
            
            # 方法2: 搜索页面中的分页模式
            import re
            page_source = self.driver.page_source
            patterns = [r'\d+-\d+\s+of\s+\d+', r'\d+\s+of\s+\d+']
            
            for pattern in patterns:
                matches = re.findall(pattern, page_source, re.IGNORECASE)
                if matches:
                    return matches[0]
            
            return None
            
        except Exception as e:
            return None
    
    def get_current_cars(self):
        """获取当前页面的车型"""
        try:
            elements = self.driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
            cars = []
            
            for element in elements:
                name = element.get_attribute('data-cy')
                visible = element.is_displayed()
                if name:
                    cars.append({'name': name, 'visible': visible, 'element': element})
            
            return cars
        except Exception as e:
            print(f"获取车型时出错: {e}")
            return []
    
    def analyze_carousel_buttons(self):
        """分析轮播按钮状态"""
        try:
            # 下一页按钮
            next_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="next"]')
            next_disabled = next_button.get_attribute('aria-disabled') == 'true'
            next_label = next_button.get_attribute('aria-label')
            
            print(f"   ▶️  下一页按钮: {'禁用' if next_disabled else '可用'} ({next_label})")
            
            # 上一页按钮
            prev_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="prev"]')
            prev_disabled = prev_button.get_attribute('aria-disabled') == 'true'
            prev_label = prev_button.get_attribute('aria-label')
            
            print(f"   ◀️  上一页按钮: {'禁用' if prev_disabled else '可用'} ({prev_label})")
            
        except Exception as e:
            print(f"   ❌ 按钮状态分析出错: {e}")
    
    def systematic_car_discovery(self):
        """系统性发现所有车型"""
        try:
            max_iterations = 10
            iteration = 0
            
            while iteration < max_iterations:
                iteration += 1
                print(f"\n   🔄 第 {iteration} 轮探索:")
                
                # 获取当前车型
                current_cars = self.get_current_cars()
                new_discoveries = 0
                
                for car in current_cars:
                    if car['name'] not in self.discovered_cars:
                        self.discovered_cars.add(car['name'])
                        new_discoveries += 1
                        print(f"      ✓ 新发现: {car['name']} ({'可见' if car['visible'] else '隐藏'})")
                
                if new_discoveries == 0:
                    print(f"      - 本轮无新发现")
                
                print(f"      📊 累计发现: {len(self.discovered_cars)} 个车型")
                
                # 更新分页信息
                pagination_info = self.get_pagination_info()
                if pagination_info:
                    print(f"      📄 分页指示器: {pagination_info}")
                    self.pagination_history.append(pagination_info)
                
                # 如果达到7个车型，成功！
                if len(self.discovered_cars) >= 7:
                    print(f"      🎉 成功发现 {len(self.discovered_cars)} 个车型!")
                    break
                
                # 尝试点击下一页
                if self.click_next_button():
                    print(f"      ✓ 成功点击下一页")
                    time.sleep(2)
                else:
                    print(f"      ❌ 无法点击下一页，探索结束")
                    break
            
            print(f"\n   📊 探索总结:")
            print(f"      - 总轮次: {iteration}")
            print(f"      - 发现车型: {len(self.discovered_cars)} 个")
            print(f"      - 车型列表: {sorted(list(self.discovered_cars))}")
            
        except Exception as e:
            print(f"   ❌ 系统性探索出错: {e}")
    
    def click_next_button(self):
        """点击下一页按钮"""
        try:
            next_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="next"]')
            aria_disabled = next_button.get_attribute('aria-disabled')
            
            if aria_disabled == 'false':
                # 记录点击历史
                self.click_history.append(f"点击下一页 (第{len(self.click_history)+1}次)")
                
                # 滚动到按钮位置
                self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", next_button)
                time.sleep(0.5)
                
                # 点击按钮
                next_button.click()
                return True
            else:
                print(f"        下一页按钮已禁用 (aria-disabled={aria_disabled})")
                return False
                
        except Exception as e:
            print(f"        点击下一页按钮出错: {e}")
            return False
    
    def click_prev_button(self):
        """点击上一页按钮"""
        try:
            prev_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="prev"]')
            aria_disabled = prev_button.get_attribute('aria-disabled')
            
            if aria_disabled == 'false':
                # 记录点击历史
                self.click_history.append(f"点击上一页 (第{len(self.click_history)+1}次)")
                
                # 滚动到按钮位置
                self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", prev_button)
                time.sleep(0.5)
                
                # 点击按钮
                prev_button.click()
                return True
            else:
                print(f"        上一页按钮已禁用 (aria-disabled={aria_disabled})")
                return False
                
        except Exception as e:
            print(f"        点击上一页按钮出错: {e}")
            return False
    
    def verify_st_edition(self):
        """验证是否找到了ST Edition车型"""
        try:
            if 'ST Edition' in self.discovered_cars:
                print(f"   ✅ 成功找到目标车型 'ST Edition'")
                
                # 尝试定位到ST Edition元素
                try:
                    st_element = self.driver.find_element(By.CSS_SELECTOR, 'div[data-cy="ST Edition"]')
                    is_visible = st_element.is_displayed()
                    print(f"   📍 ST Edition当前状态: {'可见' if is_visible else '隐藏'}")
                except:
                    print(f"   📍 ST Edition元素存在但当前不在DOM中")
                
                return True
            else:
                print(f"   ❌ 未找到目标车型 'ST Edition'")
                print(f"   📝 已发现的车型: {sorted(list(self.discovered_cars))}")
                return False
                
        except Exception as e:
            print(f"   ❌ 验证ST Edition时出错: {e}")
            return False
    
    def test_carousel_reset(self):
        """测试轮播恢复功能"""
        try:
            print(f"   🔄 测试轮播恢复功能...")
            
            # 记录当前状态
            initial_pagination = self.get_pagination_info()
            print(f"   📄 恢复前分页状态: {initial_pagination}")
            
            # 尝试使用上一页按钮回到开头
            reset_clicks = 0
            max_reset_clicks = 10
            
            while reset_clicks < max_reset_clicks:
                if self.click_prev_button():
                    reset_clicks += 1
                    print(f"      ◀️  第 {reset_clicks} 次点击上一页")
                    time.sleep(1)
                    
                    # 检查分页状态
                    current_pagination = self.get_pagination_info()
                    print(f"      📄 当前分页: {current_pagination}")
                    
                    # 如果分页显示回到了开头（如"1-X of 7"），停止
                    if current_pagination and current_pagination.startswith('1-'):
                        print(f"      ✅ 成功恢复到第一页")
                        break
                else:
                    print(f"      ❌ 无法继续点击上一页，可能已到开头")
                    break
            
            # 验证恢复后的状态
            final_pagination = self.get_pagination_info()
            print(f"   📄 恢复后分页状态: {final_pagination}")
            
            # 检查第一个车型是否重新可见
            current_cars = self.get_current_cars()
            first_cars = [car for car in current_cars if car['visible']]
            if first_cars:
                print(f"   👁️  恢复后可见车型:")
                for car in first_cars[:3]:  # 显示前3个
                    print(f"      - {car['name']}")
            
        except Exception as e:
            print(f"   ❌ 轮播恢复测试出错: {e}")
    
    def final_verification(self):
        """最终验证和总结"""
        try:
            print(f"\n📋 最终验证结果:")
            print(f"   - 期望车型数: 7")
            print(f"   - 实际发现数: {len(self.discovered_cars)}")
            print(f"   - 是否包含ST Edition: {'是' if 'ST Edition' in self.discovered_cars else '否'}")
            
            print(f"\n📝 完整车型列表:")
            for i, car_name in enumerate(sorted(self.discovered_cars), 1):
                print(f"   {i}. {car_name}")
            
            print(f"\n📄 分页历史:")
            unique_pagination = list(dict.fromkeys(self.pagination_history))  # 去重
            for info in unique_pagination:
                print(f"   - {info}")
            
            print(f"\n🖱️  点击历史:")
            for click in self.click_history:
                print(f"   - {click}")
            
            # 判断成功与否
            success = (
                len(self.discovered_cars) == 7 and 
                'ST Edition' in self.discovered_cars
            )
            
            if success:
                print(f"\n✅ 第1阶段逻辑验证: 完全成功!")
                print(f"   ✓ 找到了预期的7个车型")
                print(f"   ✓ 包含目标车型 'ST Edition'")
                print(f"   ✓ 轮播导航功能正常")
                print(f"   ✓ Cookie处理正常")
            else:
                print(f"\n⚠️  第1阶段逻辑验证: 部分成功")
                if len(self.discovered_cars) != 7:
                    print(f"   ❌ 车型数量不符: {len(self.discovered_cars)} != 7")
                if 'ST Edition' not in self.discovered_cars:
                    print(f"   ❌ 缺少目标车型 'ST Edition'")
            
            # 保存结果
            result = {
                "verification_time": time.strftime("%Y-%m-%d %H:%M:%S"),
                "success": success,
                "expected_cars": 7,
                "discovered_cars": len(self.discovered_cars),
                "has_st_edition": 'ST Edition' in self.discovered_cars,
                "car_list": sorted(list(self.discovered_cars)),
                "pagination_history": unique_pagination,
                "click_history": self.click_history
            }
            
            with open('stage1_verification_result.json', 'w', encoding='utf-8') as f:
                json.dump(result, f, indent=2, ensure_ascii=False)
            
            print(f"\n💾 验证结果已保存到 stage1_verification_result.json")
            
            return success
            
        except Exception as e:
            print(f"❌ 最终验证时出错: {e}")
            return False

def main():
    """主函数"""
    verifier = Stage1Verifier()
    success = verifier.verify_stage1_logic()
    
    if success:
        print("\n🎉 第1阶段逻辑验证完全成功！")
    else:
        print("\n❌ 第1阶段逻辑验证未完全成功！")

if __name__ == "__main__":
    main()
